<template>
  <el-dialog title="导入数据预览" v-model="visible">
    <el-table :data="importData" border style="width: 100%" ref="importTableRef">
      <el-table-column type="selection" width="55" /> 
      <el-table-column 
        v-for="(column,index) in importColumns"
        :key="column.prop || column.type" 
        :label="column.label">
        <template #default="scope">
          {{ scope.row[column.prop] }}
        </template> 
    </el-table-column> 
    </el-table>
    <p />
    <div slot="footer" style="text-align: right;">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitImport">确认导入</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref,watch } from 'vue'

const emit = defineEmits(['submitImport'])

const props=defineProps({
  importColumns:{type:Array,default:[]}
})

const visible = ref(false)
const importData = ref([])
const importTableRef = ref()

//console.log(props.columns)
const showPreview = (data) => {
  // 假设 data 是类似 [ { "姓名": "张三", "年龄": 25 }, ... ]
  const propMap = props.importColumns.reduce((map, col) => {
    map[col.label] = col.prop // 构建 label -> prop 映射表
    return map
  }, {})

  // 转换数据字段名
  importData.value = (data.data || data).map(row => {
    const newRow = {}
    for (const key in row) {
      if (propMap[key]) {
        newRow[propMap[key]] = row[key]
      } else {
        // 如果没有对应 prop，保留原 key 或忽略
        newRow[key] = row[key]
      }
    }
    return newRow
  })
  visible.value = true
}

const submitImport = async () => {
  const selectedRows = importTableRef.value.getSelectionRows()
  emit('submitImport',selectedRows)
  visible.value = false
}

watch(importData, (val) => { 
})

defineExpose({
  showPreview,
})
</script>